package com.yhsimon.syn;

//不安全的买票案例
public class UnsafeBuyTicket {
    public static void main(String[] args) {
        BuyTicket ticket=new BuyTicket();

        new Thread(ticket,"张三").start();
        new Thread(ticket,"李四").start();
        new Thread(ticket,"黄牛").start();
    }
}
class BuyTicket implements Runnable{

    private int tickets=10;
    boolean flag=true;
    @Override
    public void run() {
        while(flag){
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            buy();
        }
    }

    //加synchronized锁 :锁的是this
    private synchronized void buy() {
        if(tickets<=0){
            flag=false;
            return;
        }
        System.out.println(Thread.currentThread().getName()+"拿到"+tickets--);
    }
}